<template>
  <el-container v-loading="searchLoading">
    <el-main>
      <el-form :inline="true" ref="searchForm" :model="searchForm">
        <el-form-item label="时间" prop="startTimeStr">
          <el-date-picker
            v-model="sTime"
            type="daterange"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <!--                <el-form-item>-->
        <!--                  <el-button type="primary" @click="personalSubmit">查询</el-button>-->
        <!--                  <el-button>导出</el-button>-->
        <!--                </el-form-item>-->
        <el-form-item>
          <el-button @click="searchSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="list">
        <el-table-column type="index" label="序号"/>
        <el-table-column align="center" prop="name" label="课程名称"/>
        <el-table-column align="center" prop="joinCourseUserNumber" label="应学习人数"/>
        <el-table-column align="center" prop="noJoinCourseUserNumber" label="未学习人数"/>
        <el-table-column align="center" prop="noPassUserNumber" label="未完成人数"/>
        <el-table-column align="center" prop="passUserNumber" label="已完成人数"/>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="analysis(scope.row.id)">数据分析</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="personalLimits"
        @current-change="personalPages"
        :current-page="page"
        :page-size="limit"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes,prev, pager, next, jumper"
        :total="personalTotal"
      ></el-pagination>
    </el-main>
    <el-drawer
      title="数据分析"
      :visible.sync="drawer"
      direction="rtl"
      size="80%"
      :before-close="_=>{this.drawer = false}"
    >
      <el-tabs type="border-card" @tab-click="tabClick" v-model="tab">
        <el-tab-pane label="部门查询" name="dept" v-loading="deptLoading">
          <el-container>
            <el-header>
              <el-form :inline="true" ref="deptForm" :model="deptForm">
                <el-form-item prop="deptId" label="部门" label-width="50px">
                  <el-cascader
                    placeholder="点击选择部门"
                    :options="deptList"
                    v-model="deptForm.deptId"
                    :props="deptListTreeProps"
                    filterable
                    clearable
                    change-on-select
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="deptSubmit(1)">查询</el-button>
                  <el-button @click="examAndCert">导出</el-button>
                </el-form-item>
              </el-form>
            </el-header>
            <el-main>
              <el-table :data="deptData">
                <el-table-column align="center" type="index" label="序号"/>
                <el-table-column align="center" prop="deptName" label="部门名称"/>
                <el-table-column align="center" prop="title" label="课程名称"/>
                <el-table-column align="center" prop="courseUserNum" label="应学习人数"/>
                <el-table-column align="center" prop="passUserNum" label="已完成人数"/>
                <el-table-column align="center" prop="noPassUserNum" label="未完成人数"/>
                <el-table-column align="center" prop="noStartUserNum" label="未学习人数"/>
              </el-table>
              <el-pagination
                @size-change="deptLimit"
                @current-change="deptPage"
                :current-page="deptPages.page"
                :page-sizes="[10, 20, 50]"
                :page-size="deptPages.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="deptTotal"
              ></el-pagination>
            </el-main>
          </el-container>
        </el-tab-pane>
        <el-tab-pane label="个人查询" name="personal" v-loading="personalLoading">
          <el-container>
            <el-main>
              <el-form :inline="true" ref="personalForm" :model="personalForm">
                <el-form-item label="姓名" prop="realname">
                  <el-input v-model="personalForm.realname"></el-input>
                </el-form-item>
                <el-form-item prop="deptId" label="部门" label-width="50px">
                  <el-cascader
                    placeholder="点击选择上级部门"
                    :options="deptList"
                    v-model="personalForm.deptId"
                    :props="deptListTreeProps"
                    filterable
                    clearable
                    change-on-select
                  />
                </el-form-item>
                <el-form-item label="状态" prop="qualified">
                  <el-radio-group v-model="personalForm.qualified" @change="getUsercenterList([],1)">
                    <el-radio-button :label="1">全部</el-radio-button>
                    <el-radio-button :label="2">未学习</el-radio-button>
                    <el-radio-button :label="3">未完成</el-radio-button>
                    <el-radio-button :label="4">已完成</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="personalSubmit(1)">查询</el-button>
                  <el-button  @click="examAndCertpeople">导出</el-button>
                </el-form-item>
              </el-form>
              <el-table :data="personalData">
                <el-table-column align="center" type="index" label="序号"/>
                <el-table-column prop="realname" label="姓名"/>
                <el-table-column prop="deptName" label="部门"/>
                <el-table-column prop="courseName" label="课程名称"/>
                <el-table-column prop="coursewareStatus" label="学习状态">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.courseStatus == 0">未学习</el-tag>
                    <el-tag v-if="scope.row.courseStatus == 1">未完成</el-tag>
                    <el-tag v-if="scope.row.courseStatus == 2">已完成</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="courseExamStatus" label="考试状态">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.courseExamStatus == 0">未参加</el-tag>
                    <el-tag v-if="scope.row.courseExamStatus == 1">未通过</el-tag>
                    <el-tag v-if="scope.row.courseExamStatus == 2">已通过</el-tag>
                    <el-tag v-if="scope.row.courseExamStatus == 3">  - -  </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                @size-change="personalLimit"
                @current-change="personalPage"
                :current-page="personalPages.page"
                :page-size="personalPages.limit"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes,prev, pager, next, jumper"
                :total="total"
              ></el-pagination>
            </el-main>
          </el-container>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </el-container>
</template>

<script>
  import {treeDataTranslate} from '@/utils'

  export default {
    name: 'exam',
    data: _ => ({
      drawer: false,
      deptLoading: false,
      personalLoading: false,
      searchLoading: false,
      tab: 'dept',
      list: [], // 列表数据
      deptList: [], // 部门
      deptListTreeProps: {
        checkStrictly: true,
        expandTrigger: 'click',
        label: 'name',
        value: 'id',
        children: 'children',
        emitPath: false
      },
      searchData: '',
      searchForm: {
        startTime: '',
        endTime: '',
        type: 0
      },
      deptForm: {
        courseId: '',
        deptId: '',
        name: ''
      },
      deptData: [],
      sTime: [],
      personalForm: {
        realname: '',
        qualified: 1,
        startTime: [],
        join: '',
        deptId: '',
        date: '',
        name: '',
        type: ''
      },
      personalData: [],
      searchPages: {
        page: 1,
        limit: 10
      },
      deptPages: {
        page: 1,
        limit: 10
      },
      pageIndex: 1,
      userList: [],
      pageSize: 10,
      List: [],
      page: 1,
      limit: 10,
      deptTotal: 0,
      personalTotal: 0,
      total: 0
    }),
    mounted() {
      this.$http({
        url: this.$http.adornUrl('/usercenter-admin/dept/list'),
        method: 'post'
      }).then(res => {
        this.deptList = treeDataTranslate(
          res.data.filter(item => item.parentId !== -1),
          'id'
        )
      })
      this.searchSubmit()
    },
    methods: {
      analysis(id) {
        this.deptForm = {}
        this.tab = 'dept'
        this.deptPages.page = 1
        this.$nextTick(() => {
          this.$refs['personalForm'].resetFields()
        })
        this.drawer = true
        this.deptForm.courseId = id
        this.deptSubmit(1)
      },
      tabClick({name}) {
        if (name === 'dept') {
          this.deptSubmit(1)
        } else {
          this.personalSubmit(1)
          // this.getUsercenterList(1)
        }
      },
      searchSubmit() {
        this.searchLoading = true
        if (this.sTime && this.sTime.length) {
          this.searchForm.startTime = `${this.sTime[0] / 1000}`
          this.searchForm.endTime = `${this.sTime[1] / 1000}`
        } else {
          this.searchForm.startTime = ''
          this.searchForm.endTime = ''
        }
        this.$http({
          url: this.$http.adornUrl('/train-admin/courseStatistics/course/list'),
          method: 'post',
          data: {
            page: this.page,
            limit: this.limit,
            startTime: this.searchForm.startTime,
            endTime: this.searchForm.endTime
          }
        })
          .then(res => {
            // eslint-disable-next-line eqeqeq
            this.list = res.data ? res.data.list : []
            this.searchLoading = false
            this.personalTotal = res.data.totalCount
          })
          .catch(_ => {
            this.list = []
            this.searchLoading = false
          })
      },
      deptSubmit() {
        this.deptLoading = true
        this.$http({
          url: this.$http.adornUrl('/train-admin/courseStatistics/course/dept'),
          method: 'post',
          data: {
            courseId: this.deptForm.courseId,
            deptId: this.deptForm.deptId,
            page: this.deptPages.page,
            limit: this.deptPages.limit
          }
        })
          .then(res => {
            if (res.data) {
              this.deptTotal = res.data.totalCount
              this.deptData = res.data.list
            } else {
              this.deptTotal = 0
              this.deptData = []
            }
            this.deptLoading = false
          })
          .catch(_ => {
            this.deptLoading = false
          })
      },
      personalSubmit(val) {
        if (val) this.pageIndex = val
        let arr = ['realname', 'deptId']
        let aaaa = arr
          .map(x => this.personalForm[x])
          .filter(x => x !== '' && x !== null)
        if (aaaa.length) {
          this.$http({
            url: this.$http.adornUrl('/usercenter-admin/user/getListByQueryInfo'),
            method: 'post',
            data: {
              realname: this.personalForm.realname,
              duty: this.personalForm.duty,
              craftId: this.personalForm.craftId,
              identityCard: this.personalForm.identityCard,
              deptId: this.personalForm.deptId,
              page: this.pageIndex,
              limit: this.pageSize
            }
          }).then(res => {
            console.log(this.pageIndex)
            this.userList = res.data
            if (this.userList.length) {
              let userIds = res.data.map(x => x.userId).join(',')
              this.getUsercenterList(userIds, this.pageIndex)
            } else {
              this.userIds = -1
              this.personalData = []
              this.total = 0
            }
          })
        } else {
          this.userIds = null
          this.getUsercenterList()
        }
      },
      getUsercenterList(userIds, page) {
        this.personalLoading = true
        this.dataExam = []
        this.data = []
        if (page) this.pageIndex = page
        // this.userIds = this.List.map(x => x.userId).join(',')
        // this.userIds = this.personalData.map(x => x.userId)
        // eslint-disable-next-line eqeqeq
        this.$http({
          url: this.$http.adornUrl('/train-admin/sta/user'),
          method: 'post',
          data: {
            searchUserIds: userIds,
            realname: this.personalForm.realname,
            courseId: this.deptForm.courseId,
            deptId: this.personalForm.deptId,
            courseStatus: this.personalForm.qualified,
            page: this.pageIndex,
            limit: this.pageSize
            // startTime:
            //   this.personalForm.startTime[0] / 1000
            //     ? this.personalForm.startTime[0]
            //     : '',
            // endTime:
            //   this.personalForm.startTime[1] / 1000
            //     ? this.personalForm.startTime[1]
            //     : ''
          }
        }).then(data => {
          if (data.code === 200) {
            this.personalData = data.data.list
            this.total = data.data.totalCount
            this.personalPages.page = data.data.currPage
            this.personalPages.limit = data.data.pageSize
            this.personalLoading = false
          } else {
            this.personalData = []
            this.$notify.error({
              title: '失败',
              message: '暂无人员列表'
            })
          }
        })
      },
      deptLimit(val) {
        this.deptPages = {
          page: 1,
          limit: val
        }
        this.deptSubmit()
      },
      deptPage(val) {
        this.deptPages.page = val
        this.deptSubmit()
      },
      personalLimit(val) {
        this.pageSize = val
        this.pageIndex = 1
        if (this.personalForm.realname || this.personalForm.deptId) {
          console.log(this.personalForm.realname)
          this.personalSubmit(val)
        } else {
          this.getUsercenterList()
        }
      },
      personalPage(val) {
        this.pageIndex = val
        this.pageSize = 10
        if (this.personalForm.realname || this.personalForm.deptId) {
          this.personalSubmit(val)
        } else {
          this.getUsercenterList()
        }
      },
      personalLimits(val) {
        this.limit = val
        this.page = 1
        this.searchSubmit()
      },
      personalPages(val) {
        this.page = val
        this.limit = 10
        this.searchSubmit()
      },
      // 部門导出
      examAndCert() {
        this.$http({
          url: this.$http.adornUrl(`/train-admin/courseStatistics/course/dept`),
          method: 'post',
          data: {
            page: 1,
            limit: 99999,
            deptId: this.personalForm.deptId,
            courseId: this.deptForm.courseId
          }
        }).then(res => {
          // eslint-disable-next-line no-undef,eqeqeq
          let dataList = res && res.code == 200 ? res.data.list : []
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              '课程名称',
              '部门',
              '应学习人数',
              '已完成人数',
              '未完成人数',
              '未学习人数'
            ]
            const filterVal = [
              'title',
              'deptName',
              'courseUserNum',
              'passUserNum',
              'noPassUserNum',
              'noStartUserNum'
            ]
            const data = this.formatJson(filterVal, dataList)
            // data.forEach((x, i) => (x[0] = i + 1))
            excel.export_json_to_excel({
              header: tHeader,
              data,
              // filename: `"${res.data.list[0].examName}"安全考试成绩汇总表${new Date().toLocaleDateString()}`
              filename: '学习部门数据导出'
            })
          })
        })
      },
      // 学习导出
      examAndCertpeople () {
        window.location = this.$http.downloadUrl(
          '/train-admin/courseManage/userCourseListExport',
          {
            courseId: this.deptForm.courseId,
            courseStatus: this.personalForm.qualified
          }
        )
      },
      // examAndCertpeople() {
      //   // eslint-disable-next-line one-var
      //   let coursewareCount = 0, examCount = 0
      //   this.$http({
      //     url: this.$http.adornUrl(
      //       `/train-admin/courseManage/usercourselistexport`
      //     ),
      //     method: 'post',
      //     data: {
      //       page: 1,
      //       limit: 99999,
      //       courseId: this.deptForm.courseId
      //     }
      //   }).then(res => {
      //     coursewareCount = res.data.coursewareCount
      //     examCount = res.data.examCount
      //     // eslint-disable-next-line no-undef,eqeqeq
      //     let dataList = res && res.code == 200 ? res.data.courseList : []
      //     dataList.map(x => (x.coursewareStatus = x.coursewareStatus === 0 ? '未学习' : x.courseStatus === 1 ? '未完成' : '已完成'))
      //     dataList.map(x => (x.courseExamStatus = x.courseExamStatus === 0 ? '未参加' : x.courseStatus === 1 ? '未通过' : '已通过'))
      //     dataList.map(x => (x.courseStatus = x.courseStatus === 0 ? '未学习' : x.courseStatus === 1 ? '未完成' : '已完成'))
      //     import('@/vendor/Export2Excel').then(excel => {
      //       let tHeader = [
      //         '姓名',
      //         '部门',
      //         '课程名称'
      //       ]
      //       if (coursewareCount > 0) tHeader.push('学习状态')
      //       if (examCount > 0) tHeader.push('考试状态')
      //       tHeader.push('总状态')
      //       const filterVal = [
      //         'realname',
      //         'deptName',
      //         'courseName'
      //       ]
      //
      //       if (coursewareCount > 0) filterVal.push('courseStatus')
      //       if (examCount > 0) filterVal.push('courseExamStatus')
      //       filterVal.push('courseStatus')
      //       const data = this.formatJson(filterVal, dataList)
      //       excel.export_json_to_excel({
      //         header: tHeader,
      //         data,
      //         // filename: `"${res.data.list[0].examName}"安全考试成绩汇总表${new Date().toLocaleDateString()}`
      //         filename: '学习管理'
      //       })
      //     })
      //   })
      // },
      formatJson: (filterVal, jsonData) =>
        jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
</script>

<style scoped>
</style>
